<template>
  <div class="setting">
    <div class="setting_box">
      <div class="title">信息设置</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="头像:" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称:" prop="nickName">
          <el-input placeholder="请输入昵称" v-model="ruleForm.nickName" />
        </el-form-item>
        <el-form-item label="手机号码:" prop="phonenumber">
          <el-input
            placeholder="请输入手机号码"
            v-model="ruleForm.phonenumber"
          />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-select
            v-model="ruleForm.sex"
            placeholder="请选择性别"
            style="width: 240px"
          >
            <el-option
              v-for="item in sexList"
              :key="item.value"
              :label="item?.label"
              :value="item?.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="update">修改</el-button>
        </el-form-item>
      </el-form>
      <div class="title">账号设置</div>
      <el-form
        ref="ruleFormRef2"
        :model="ruleForm2"
        :rules="rules2"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="旧密码:" prop="oldPassword">
          <el-input
            placeholder="请输入旧密码"
            v-model="ruleForm2.oldPassword"
          />
        </el-form-item>
        <el-form-item label="新密码:" prop="newPassword">
          <el-input
            placeholder="请输入新密码"
            v-model="ruleForm2.newPassword"
          />
        </el-form-item>
        <el-form-item label="确认密码:" prop="comfirmPassword">
          <el-input
            placeholder="请输入新密码"
            v-model="ruleForm2.comfirmPassword"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePasswordFun">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { updateUserInfo, updatePassword } from "@/api/user/user";
import { useUserStoreHook } from "@/store/modules/user";
import { sexList } from "@/enums/enum";
import type { FormInstance, FormRules, UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { imageUpload } from "@/api/common/index";
import { QNURL } from "@/config/urlConfig";
import { Plus } from "@element-plus/icons-vue";

const userStore = useUserStoreHook();

const props = defineProps({
  userInfo: {
    type: Object
  }
});

const emit = defineEmits(["updateUserInfoSuccess"]);

const { userInfo } = toRefs(props);

interface RuleForm {
  id: string;
  avatar: string;
  sex: number;
  nickName: string;
  phonenumber: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  id: userStore.getUserInfo?.userId as string,
  avatar: "",
  sex: 0,
  nickName: "",
  phonenumber: ""
});

const rules = reactive<FormRules<RuleForm>>({
  sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  nickName: [{ required: true, message: "请填写昵称", trigger: "blur" }]
});

interface RuleForm2 {
  oldPassword: string;
  newPassword: string;
  comfirmPassword: string;
}

const ruleFormRef2 = ref<FormInstance>();
const ruleForm2 = reactive<RuleForm2>({
  oldPassword: "",
  newPassword: "",
  comfirmPassword: ""
});

const rules2 = reactive<FormRules<RuleForm2>>({
  oldPassword: [{ required: true, message: "请填写旧密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请填写新密码", trigger: "blur" }],
  comfirmPassword: [
    { required: true, message: "请填写确认密码", trigger: "blur" }
  ]
});

const imageUrl = ref("");
const imgName = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log(imageUrl.value);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = file => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJpgOrPng) {
    ElMessage.error("只能上传 JPG/PNG 图片格式的文件");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("文件大小超过 2MB 的限制");
    return false;
  }

  // 使用自定义的方式上传文件
  const formData = new FormData();
  formData.append("image", file);

  uploadFile(formData);

  return false;
};

const uploadFile = async (formData: FormData) => {
  console.log(formData);
  // 自定义上传方法
  // 在这里可以使用你喜欢的方式发送文件上传请求，例如使用axios或者fetch
  // 替换为你自己的上传地址
  // const uploadUrl = "/upload";
  // 发送请求上传文件
  // 例如使用axios：
  try {
    const res = await imageUpload(formData);
    if (res.code === 200) {
      imageUrl.value = QNURL + res?.msg;
      imgName.value = res?.msg;
    }
  } catch (error) {
    console.error(error);
  }
};

async function update() {
  ruleFormRef.value &&
    ruleFormRef.value.validate(async valid => {
      if (valid) {
        //
        if (imgName.value) {
          ruleForm.avatar = imgName.value;
        }
        const res = await updateUserInfo(ruleForm);

        if (res.code !== 200) return;

        userStore.SET_USER_INFO(ruleForm);

        emit("updateUserInfoSuccess");
        ElMessage.success("修改成功");
      } else {
        ElMessage.error("请填写完整信息");
      }
    });
}

function updatePasswordFun() {
  ruleFormRef2.value &&
    ruleFormRef2.value.validate(async valid => {
      if (valid) {
        //
        if (ruleForm2.newPassword !== ruleForm2.comfirmPassword) {
          ElMessage.error("两次输入的密码不一致");
          return;
        }

        const res = await updatePassword(ruleForm2);

        if (res.code !== 200) return;

        ElMessage.success("修改成功");
      } else {
        ElMessage.error("请填写完整信息");
      }
    });
}

watch(
  () => userInfo?.value,
  () => {
    if (userInfo?.value) {
      ruleForm.avatar = userInfo?.value.avatar;
      ruleForm.nickName = userInfo?.value.nickName;
      ruleForm.sex = Number(userInfo?.value.sex);
      imageUrl.value = QNURL + userInfo?.value.avatar;

      console.log(userInfo?.value);
    }
  },
  { deep: true }
);

onMounted(() => {});
</script>

<style lang="scss" scoped>
.setting {
  width: 100%;
  height: 100%;
  padding: 20px;

  .setting_box {
    width: 500px;

    .title {
      width: 100%;
      // background-color: red;
      height: 50px;
      line-height: 50px;
      font-size: 18px;
      font-weight: bold;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 20px;
    }

    .item {
      width: 100%;
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .avatar {
        width: 80px;
        height: 80px;
      }

      .label {
        width: 100px;
      }

      .value {
      }

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.setting_box {
  :deep(.avatar-uploader) {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 80px;
      height: 80px;
      transition: var(--el-transition-duration-fast);

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  :deep(.avatar-uploader) {
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  }

  :deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
